/*
 *   Copyright 1999-2018 dragonshard.net.
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *        http://www.apache.org/licenses/LICENSE-2.0
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */
package net.dragonshard.dsf.core.toolkit;


import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.Objects;


/**
 * 枚举处理工具类
 *
 * @author hubin
 */
public class EnumUtils {

  /**
   * 值映射为枚举
   *
   * @param enumClass 枚举类
   * @param value 枚举值
   * @param method 取值方法
   * @param <E> 对应枚举
   * @return 枚举
   */
  public static <E extends Enum<?>> E valueOf(Class<E> enumClass, Object value, Method method) {
    E[] es = enumClass.getEnumConstants();
    for (E e : es) {
      Object evalue;
      try {
        method.setAccessible(true);
        evalue = method.invoke(e);
      } catch (IllegalAccessException | InvocationTargetException e1) {
        throw ExceptionUtils.get("Error: NoSuchMethod in %s.  Cause:", e, enumClass.getName());
      }
      if (value instanceof Number && evalue instanceof Number
        && new BigDecimal(String.valueOf(value)).compareTo(new BigDecimal(String.valueOf(evalue)))
        == 0) {
        return e;
      }
      if (Objects.equals(evalue, value)) {
        return e;
      }
    }
    return null;
  }

}
